<?php

namespace Home\Model;

use Think\Model;
use Home\Model\ArticleModel;
use Home\Model\SiteModel;
use Home\Model\SearchLogModel;

class SearchModel extends Model {
	protected $trueTableName = '';
	/**
	 * 搜索列表
	 *
	 * @param number $where
	 * @param number $page
	 * @param string $order
	 * @param intval $num
	 *        	每页显示条数
	 * @return unknown
	 */
	public function search($keyword) {
		$keyword = str_replace ( '/', '', rtrim ( $keyword, '/' ) );
		$allkey = $this->_getAllTag ();
		$page = intval ( $_REQUEST ['page'] ) < 1 ? 1 : $_REQUEST ['page'];
		$num = C ( 'page_num' );
		$startpage = ($page - 1) * $num;

		// 读取缓存
		$cacheName = get_cache_name ( 'search_' . $keyword . ';page:' . $page . ';num:' . $num );
		$result = S ( $cacheName );
		if (! $result) {
			$where = "name like '%{$keyword}%' or tag like '%{$keyword}%' ";
			for($i = 2; $i <= (mb_strlen ( $keyword, 'utf-8' ) - 1); $i ++) {
				$where .= ' or name like "%' . mb_substr ( $keyword, 0, $i, 'utf-8' ) . '%"';
			}

			// 从所有tag去匹配
			foreach ( $allkey as $v ) {
				if (strpos ( $keyword, $v ['name'] ) !== false) {
					$where .= ' or tag like "%' . $v ['name'] . '%"';
					$where .= ' or name like "%' . $v ['name'] . '%"';
				}
			}
			$sql = 'SELECT * FROM search WHERE ' . $where . ' ORDER BY obj_type desc, updatetime desc limit ' . $startpage . ',' . intval ( $num );
			// die ( $sql );
			$total = $this->query ( "select count(*) as total_num from search where {$where}" );
			$result ['total_num'] = $total [0] ['total_num'];

			$result ['list'] = $this->query ( $sql );

			foreach ( $result ['list'] as $k => $v ) {
				if ($v ['obj_type'] == 'site') {
					$site = new SiteModel ();
					$result ['list'] [$k] = $site->getInfo ( $v ['obj_id'] );
				} elseif ($v ['obj_type'] == 'article') {
					$article = new ArticleModel ();
					$result ['list'] [$k] = $article->getInfo ( $v ['obj_id'] );
				}
			}
			$result ['page'] = page_html ( $result ['total_num'], $page, $num );
			$result ['total_page'] = ceil ( $result ['total_num'] / $num );
			if ($result ['total_page'] > $page) {
				$result ['next_page'] = $page + 1;
			} else {
				$result ['next_page'] = '';
			}
			if ($page > 1) {
				$result ['prev_page'] = $page - 1;
			} else {
				$result ['prev_page'] = '';
			}

			// 获取关键词介绍
			$site = new SiteModel ();
			$siteInfo = $site->where ( 'name="' . $keyword . '"' )->find ();
			$result ['siteIntro'] = $siteInfo ['intro'];

			S ( $cacheName, $result, C ( 'cache_time_short' ) );
		}
		// 记录搜索记录及结果
		$searchlog = new SearchLogModel ();
		$data = array (
				'num' => $result ['total_num'],
				'keyword' => $keyword
		);
		$searchlog->saveData ( $data );

		return $result;
	}

	/**
	 * 全文搜索
	 *
	 * @param unknown $keyword
	 * @param string $tags
	 * @param string $type
	 *        	site|article
	 * @return Ambigous <mixed, \Think\mixed, object>
	 */
	public function searchAll($keyword, $tags = '', $type = '') {
		$keyword = str_replace ( '/', '', rtrim ( $keyword, '/' ) );
		$allkey = $this->_getAllTag ();
		$num = 7;

		// 读取缓存
		$cacheName = get_cache_name ( 'searchall_' . $keyword . ';type:' . $type . ';tags:' . $tags.';num:'.$num );
		$result = S ( $cacheName );
		if (! $result) {
			if($keyword){
				$where = "name like '%{$keyword}%' or tag like '%{$keyword}%' ";
			}else{
				$where = '0';
			}
			for($i = 2; $i <= (mb_strlen ( $keyword, 'utf-8' ) - 1); $i ++) {
				if ($i > 14) {
					break;
				}
				$where .= ' or name like "%' . mb_substr ( $keyword, 0, $i, 'utf-8' ) . '%"';
			}

			if ($tags) {
				$keywordStr = $keyword . ',' . $tags; // 合并标题和标签
			}
			// 从所有tag去匹配
			foreach ( $allkey as $v ) {
				if (strpos ( $keywordStr, $v ['name'] ) !== false) {
					$where .= ' or tag like "%' . $v ['name'] . '%"';
					$where .= ' or name like "%' . $v ['name'] . '%"';
				}
			}
			if ($type == 'site') {
				$where = "({$where}) and obj_type='site'";
			} elseif ($type == 'article') {
				$where = "({$where}) and obj_type='article'";
			}
			$sql = 'SELECT * FROM search WHERE ' . $where . ' ORDER BY viewnum desc limit ' . intval ( $num );
			//die ( $sql );
			$total = $this->query ( "select count(*) as total_num from search where {$where}" );
			$result ['total_num'] = $total [0] ['total_num'];

			$result ['list'] = $this->query ( $sql );

			foreach ( $result ['list'] as $k => $v ) {
				if ($v ['obj_type'] == 'site') {
					$site = new SiteModel ();
					$result ['list'] [$k] = $site->getInfo ( $v ['obj_id'] );
				} elseif ($v ['obj_type'] == 'article') {
					$article = new ArticleModel ();
					$result ['list'] [$k] = $article->getInfo ( $v ['obj_id'] );
				}
			}
			$result ['page'] = page_html ( $result ['total_num'], $page, $num );
			$result ['total_page'] = ceil ( $result ['total_num'] / $num );
			if ($result ['total_page'] > $page) {
				$result ['next_page'] = $page + 1;
			} else {
				$result ['next_page'] = '';
			}
			if ($page > 1) {
				$result ['prev_page'] = $page - 1;
			} else {
				$result ['prev_page'] = '';
			}

			// 获取关键词介绍
			$site = new SiteModel ();
			$siteInfo = $site->where ( 'name="' . $keyword . '"' )->find ();
			$result ['siteIntro'] = $siteInfo ['intro'];

			S ( $cacheName, $result, C ( 'cache_time_long' ) );
		}
		return $result;
	}
	private function _getAllTag() {

		// 读取缓存
		$cacheName = get_cache_name ( 'alltag' );
		$result = S ( $cacheName );
		if ($result) {
			return $result;
		}
		$sql = "SELECT `name` FROM hua_site WHERE LENGTH(`name`)<14 and LENGTH(`name`)>4 GROUP BY `name` ORDER BY LENGTH(`name`) asc ";
		$result = $this->query ( $sql );
		S ( $cacheName, $result, C ( 'cache_time_long' ) );
		return $result;
	}
}
